package homework3;

import java.io.File;

public class FolderSizeCalculator {
    public static void main(String[] args) {
        File folder = new File("E:\\课件保存处\\itheima-课程保存包");
        long size = calculateFolderSize(folder);
        System.out.println("文件夹大小: " + formatSize(size));
    }

    private static long calculateFolderSize(File folder) {
        if (!folder.isDirectory()) {
            throw new IllegalArgumentException("给定路径不是一个文件夹");
        }

        long size = 0;
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    size += file.length();
                } else {
                    size += calculateFolderSize(file);
                }
            }
        }

        return size;
    }

    private static String formatSize(long size) {
        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int index = 0;
        double formattedSize = size;
        while (formattedSize >= 1024 && index < units.length - 1) {
            formattedSize /= 1024;
            index++;
        }
        return String.format("%.2f %s", formattedSize, units[index]);
    }
}